package com.jagochan.mall.common.util;//package org.springblade.file.util;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jagochan.mall.config.MinioConfig;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;

import io.minio.messages.Item;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@SuppressWarnings("Duplicates")
@Slf4j
@Component
public class MinioUtil {
    @Resource
    private MinioConfig minioConfig;

    @Resource
    private MinioClient minioClient;

    /**
     * 查看存储bucket是否存在
     */
    public Boolean bucketExists(String bucketName) {
        boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            log.error("Minio错误: ", e);
            return false;
        }
        return found;
    }

    /**
     * 检查存储桶是否存在，不存在则创建
     */
    public void checkBucket(String bucketName) throws Exception {
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    /**
     * 创建存储bucket
     *
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            log.error("Minio错误: ", e);
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     *
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            log.error("Minio错误: ", e);
            return false;
        }
        return true;
    }

    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            log.error("Minio错误: ", e);
        }
        return null;
    }


    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    public String upload(String folder, MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new RuntimeException();
        }
        String fileName = IdUtil.simpleUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = folder + "/" + DateUtil.format(DateUtil.date(), "yyyy/MM/dd") + "/" + fileName;
        try {
            checkBucket(minioConfig.getBucketName());
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minioConfig.getBucketName()).object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            log.error("Minio错误: ", e);
            return null;
        }
        return objectName;
    }

    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new RuntimeException();
        }
        String fileName = IdUtil.simpleUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = DateUtil.format(DateUtil.date(), "yyyy/MM/dd") + "/" + fileName;
        try {
            checkBucket(minioConfig.getBucketName());
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minioConfig.getBucketName()).object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            log.error("Minio错误: ", e);
            return null;
        }
        return objectName;
    }

    /**
     * 文件上传
     *
     * @param bucketName    桶
     * @param fileName      文件名
     * @param multipartFile 文件
     */
    public String uploadFile(String bucketName, String fileName, MultipartFile multipartFile) throws IOException {
        String url;
        MinioClient minioClient = SpringUtil.getBean(MinioClient.class);
        try (InputStream inputStream = multipartFile.getInputStream()) {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                checkBucket(bucketName);
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                // bucket权限-读写
                String READ_WRITE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\",\"s3:AbortMultipartUpload\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "/*\"]}]}";
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(READ_WRITE).build());
            }
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
                    .object(fileName)
                    .stream(inputStream, multipartFile.getSize(), -1)
                    .contentType(multipartFile.getContentType()).build()
            );
            //路径获取
            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(fileName).
                    method(Method.GET).build());
            url = url.substring(0, url.indexOf('?'));
            //常规访问路径获取
            return url;
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 预览图片
     */
    public String preview(String fileName) {
        // 查看文件地址
        GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs
                .builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .method(Method.GET)
                .build();
        try {
            return minioClient.getPresignedObjectUrl(build);
        } catch (Exception e) {
            log.error("Minio错误: ", e);
        }
        return null;
    }

    /**
     * 获取文件预览链接(7天有效)
     */
    public String getFileUrl(String objectName) throws Exception {
        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .bucket(minioConfig.getBucketName())
                        .object(objectName)
                        .expiry(7 * 24 * 60 * 60) // 7天有效期
                        .build());
    }

    /**
     * 文件下载
     *
     * @param fileName 文件名称
     * @param res      response
     */
    public void download(String fileName, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(minioConfig.getBucketName())
                .object(fileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
                while ((len = response.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                // 设置强制下载不打开
                // res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()) {
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            log.error("Minio错误: ", e);
        }
    }

    /**
     * 查看文件对象
     *
     * @return 存储bucket内文件对象信息
     */
    public List<Item> listObjects() {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(minioConfig.getBucketName()).build());
        List<Item> items = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                items.add(result.get());
            }
        } catch (Exception e) {
            log.error("Minio错误: ", e);
            return null;
        }
        return items;
    }

    /**
     * 删除
     */
    public boolean remove(String fileName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).build());
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 删除文件夹及文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件或文件夹名称:以.结尾为文件,以/结尾为文件夹
     */
    public boolean deleteObjects(String bucketName, String objectName) {
        if (StrUtil.isNotBlank(objectName)) {
            if (objectName.endsWith(".") || objectName.endsWith("/")) {
                Iterable<Result<Item>> list = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(true).build());
                ExecutorService executorService = Executors.newFixedThreadPool(10);
                list.forEach(e -> {
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(e.get().objectName()).build());
                            } catch (ErrorResponseException | InsufficientDataException | InternalException |
                                     InvalidResponseException | IOException | InvalidKeyException | ServerException |
                                     XmlParserException | NoSuchAlgorithmException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    });
                });
                executorService.shutdown();
                return true;
            }
        }
        return true;
    }

    /**
     * 清除指定存储桶中7天前的文件
     *
     * @param bucketName 存储桶名称
     * @param folderPath 文件夹路径（如 "logs/"）
     */
    public void cleanupOldFiles(String bucketName, String folderPath, long days) {
        try {
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 计算days天前的时间
            LocalDateTime sevenDaysAgo = now.minusDays(days);
            // 转换为 Date 对象
            Date cutoffDate = Date.from(sevenDaysAgo.atZone(ZoneId.systemDefault()).toInstant());

            // 列出指定文件夹下的所有对象
            ListObjectsArgs listArgs = ListObjectsArgs.builder()
                    .bucket(bucketName)
                    .prefix(folderPath)
                    .recursive(true)
                    .build();
            Iterable<Result<Item>> results = minioClient.listObjects(listArgs);

            // 遍历文件并删除超过7天的文件
            for (Result<Item> result : results) {
                Item item = result.get();
                Date lastModified = Date.from(item.lastModified().toInstant());
                if (lastModified.before(cutoffDate)) {
                    minioClient.removeObject(RemoveObjectArgs.builder()
                            .bucket(bucketName)
                            .object(item.objectName())
                            .build());
                    System.out.println("Deleted  file: " + item.objectName());
                }
            }
        } catch (Exception e) {
            log.error("Minio错误: ", e);
        }
    }
}

